package srvctx

import (
	"gitee.com/mkwchecking/sr-core/domain/dao/scope"
	"gitee.com/mkwchecking/sr-core/log"
	"gitee.com/mkwchecking/sr-core/net/http/session"
	"gitee.com/mkwchecking/sr-core/yerr"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

var (
	TraceKey = "X-Request-Id"
)

func New(ctx *gin.Context) *Context {

	traceId := ctx.GetString(TraceKey)
	if traceId == "" {
		traceId = uuid.NewString()
		ctx.Header(TraceKey, traceId)
	}

	gctx := &Context{
		ctx:     ctx,
		traceId: traceId,
	}

	gctx.session, _ = session.GetManagerMW(ctx)

	return gctx
}

type Context struct {
	ctx     *gin.Context
	traceId string
	session *session.SessionManager
	logger  log.Logger
}

func (c *Context) TraceId() string {
	return c.traceId
}

func (c *Context) Logger() log.Logger {
	if c.logger == nil {
		c.logger = log.GetDefault()
	}
	return c.logger
}

func (c *Context) SetLogger(logger log.Logger) {
	c.logger = logger
}

func (c *Context) Session() *session.SessionManager {
	return c.session
}

func (c *Context) SessionStore() (session.Storage, error) {
	if c.session == nil {
		return nil, yerr.ErrBizPluginNotFound.Error("session")
	}

	return c.session.GetStore(), nil
}

func (c *Context) GetSessionInfo() (*session.Info, error) {
	if c.session == nil {
		return nil, yerr.ErrBizPluginNotFound.Error("session")
	}

	sessinfo, err := c.session.GetSessionInfo(c, c.ctx.Request)
	if err != nil {
		return nil, err
	}

	return session.ScanInfo(sessinfo)
}

func (c *Context) GetSessionId() (string, error) {
	if c.session == nil {
		return "", yerr.ErrBizPluginNotFound.Error("session")
	}

	return c.session.GetSessionId(c.ctx.Request)
}

func (c *Context) DaoScope() scope.IScope {
	sessInfo, err := c.GetSessionInfo()
	if err != nil {
		return nil
	}
	return scope.WithOperator(sessInfo)
}
